<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索段 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!----------------- 添加用户功能------------------------>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          <!-- 添加用户表单 -->
          <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
            <el-form
              :model="addForm"
              :rules="addFormRules"
              ref="addFormRef"
              label-width="70px"
              class="demo-ruleForm"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password" type="password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="item">
            <el-switch v-model="item.row.mg_state" @change="userStateChanged(item.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190">
          <template slot-scope="item">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(item.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(item.row.id)"
            ></el-button>
            <!-- 分配角色 -->

            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(item.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 编辑用户 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogClosed"
        width="50%"
        @close="editDialogVisibleClosed"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogClosed = false">取 消</el-button>
          <el-button type="primary" @click="subEdit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleVisible" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户{{userInfo.username}}</p>
        <p>当前的角色{{userInfo.role_name}}</p>
        <p>
          分配角色:
          <el-select v-model="selectId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo" >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { userInfo } from 'os';
export default {
  data() {
    //   验证邮箱规则
    let checkEmail = (rule, value, cb) => {
      const regEmail = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/
      if (regEmail.test(value)) {
        //    合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    let checkMobile = (rule, value, cb) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regMobile.test(value)) {
        //    合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      queryInfo: {
        //获取用户列表的参数对象
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      // 用户列表数据
      userList: [],
      total: 0,
      dialogVisible: false,
      //   添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //编辑表单
      editForm: {},
      // 编辑弹窗
      editDialogClosed: false,
      //添加规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名的长度在6-13个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //   编辑规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //分配角色的修改与隐藏
      setRoleVisible: false,
      // 需要被分配角色的对象
      userInfo: {},
      //角色集合名字
      roleList: [],
      //已选中角色id
      selectId:''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      var { data: res } = await this.axios.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status != 200) {
        return this.$message.error('服务器错误')
      }
      this.userList = res.data.users
      this.total = res.data.total
      //   console.log(this.userList)
    },
    //   监听pagesize改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户成功')
    },
    // 监听添加用户对话框关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async flag => {
        // console.log(flag)
        if (flag) {
          var { data: res } = await this.axios.post('users', this.addForm)
          console.log(res)
          if (res.meta.status == 201) {
            this.$message.success('亲，你创建的用户成功')
          } else {
            this.$message.error('创建用户失败哦，可能是服务器原因')
          }
          this.dialogVisible = false
        }
      })
    },
    // 展示编辑弹窗
    async showEditDialog(id) {
      //   console.log(id)
      var { data: res } = await this.axios.get('users/' + id)
      //   console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('服务器错误')
      } else {
        this.editForm = res.data
        this.editDialogClosed = true
      }
    },
    // 编辑确定时
    editDialogVisibleClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //编辑用户
    subEdit() {
      // console.log(this.$refs.editFormRef.validate)
      this.$refs.editFormRef.validate(async flag => {
        console.log(this.editForm)
        if (flag) {
          var { data: res } = await this.axios.put(
            'users/' + this.editForm.id,
            {
              email: this.editForm.email,
              mobile: this.editForm.mobile
            }
          )
          if (res.meta.status == 200) {
            this.$message.success('亲，修改成拱了')
          } else {
            this.$message.error('修改失败')
          }
          this.editDialogClosed = false
          this.getUserList()
        }
      })
      return
      this.editDialogClosed = false
    },
    //删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户，是否继续',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult == 'confirm') {
        console.log('用户确认删除')
        var { data: res } = await this.axios.delete('users/' + id)
        console.log(res)
        if (res.meta.status == 200) {
          this.$message.success('删除用户成功')
          this.getUserList()
        } else {
          this.$message.error('服务器错误，删除失败')
        }
      } else {
        this.$message.info('用户取消删除')
      }
      // console.log(confirmResult)
    },
    //设置用户角色
    async setRole(userInfo) {
      this.userInfo = userInfo
      console.log(userInfo)
      const { data: res } = await this.axios.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      console.log(res)
      this.roleList = res.data

      this.setRoleVisible = true
    },
    setRoleDialogClosed(){
      this.userInfo = {}
      this.selectId = ''
    },
    //保存新建的角色
    async saveRoleInfo(){
      if(this.selectId == ''){
        this.$message.error("请选择分配角色")
      }
      const {data:res} = await this.axios.put(`users/${this.userInfo.id}/role`,{
        rid:this.selectId
      })
      console.log(res)
      if(res.meta.status !==200){
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      this.getUserList()
      this.setRoleVisible = false;
     
    }
  }
}
</script>

<style lang='less' scoped>
</style>
